<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>

<style type="text/css">
    .autocomplete-suggestions {
        border: 1px solid #999;
        background: #FFF;
        overflow: auto;
    }

    .autocomplete-suggestion {
        padding: 2px 5px;
        white-space: nowrap;
        overflow: hidden;
    }

    .autocomplete-selected {
        background: #F0F0F0;
    }

    .autocomplete-suggestions strong {
        font-weight: normal;
        color: #3399FF;
    }

    @-moz-document url-prefix() {
        fieldset {
            display: table-cell;
        }
    }

    .recommendInput {
        width: 84px;
        height: 24px;
    }

</style>
<title>推荐订单完成率 - 云超市</title>
<%--<jsp:include page="../../head.jsp"/>--%>

<div class="" id="app">
    <form class="form-inline" style="margin-top: 20px; margin-bottom: 5px;">
        <div class="form-group">
            <input id="custCodeInput" onfocus="this.value=''" class="form-control input-sm" type="text" placeholder="请选择客户">
        </div>
        <div class="form-group">
            <input id="yearMothInput" class="form-control input-sm" type="text" placeholder="请选择年月">
        </div>
<%--        <div class="form-group">
            <select class="form-control input-sm" title="排序方式" id="orderByNameInput">
                <option value="CUST_CODE">本月已购</option>
                <option value="CUST_NAME">同期数量</option>
                <option value="LAST_INVENTORY" selected>上期数量</option>
                <option value="PERIOD_ORDER_QUANTITY">推荐数量</option>
            </select>
            <select class="form-control input-sm" id="orderByTypeInput">
                <option value="ASC">正序</option>
                <option value="DESC" selected>倒序</option>
            </select>
        </div>--%>
        <button type="button" class="btn btn-sm btn-success" @click="getOrder();">查询</button>
        <button type="button" class="btn btn-sm btn-primary" @click="saveData();">保存</button>
        <button type="button" class="btn btn-sm btn-info" @click="addRecommend()">添加客户</button>
      <%--  <button type="button" class="btn btn-sm btn-success" @click="computeRecommend();"
                title="默认计算推荐量为零的数据，如需计算推荐量不为零的数据请选中该数据">计算推荐量
        </button>--%>
    </form>

    <div class="row" style="background-color: rgb(53, 147, 202);margin-right: 0px;margin-left: 0px; height: 37px;">
        <div class="col-sm-10" style="margin-top: 6px;">
            <strong style="font-size: 18px;color: #f9f9f9;">推荐订单完成率列表</strong>
        </div>
        <div class="col-sm-2" style="text-align: right">

        </div>
    </div>
    <div class="table-responsive" id="tableContainer" style="height: 365px">
        <table class="table table-striped table-condensed table-bordered">
            <thead style="background-color:#eee;">
            <tr>
                <th>
                    <button @click="clickAllSB();">{{isAllS ? '全不选' : '全选'}}</button>
                </th>
                <th>专卖证号</th>
                <th>客户名称</th>
                <th>年月</th>
                <th>本月已购量(条)</th>
                <th>同期数量(条)</th>
                <th>同期增长率</th>
                <th>上期数量(条)</th>
                <th>上期增长率</th>

                <th>推荐数量(条)</th>
                <th>完成率</th>
                <th>偏离度</th>
                <%--<th>操作时间</th>--%>

            </tr>
            </thead>
            <tbody>

            <tr v-for="(order, index) in orderList">
                <td><input type="checkbox" v-model="order.CHECK"></td>
                <td><a title="制定详细计划" style="color: #0aa5df;" href="javascript:void(0);" @click="goToRecommendPage(order.CUST_CODE,order.YEAR_MOTH, order.CURRENT_ALREADY,order.RECOMMEND_NUM)">{{order.CUST_CODE}}</a></td>
                <td>{{order.CUST_NAME}}</td>
                <td>{{order.YEAR_MOTH}}</td>
                <td>{{order.CURRENT_ALREADY}}</td>
                <td>{{order.TCP_NUM}}</td>
                <td onclick="clickRecommendNum(this);">
                    <span>{{order.GROWTH_RATE}}</span>
                    <input min="0" onclick="stopD()" @blur="computeRecommend1(index,$event)" type="number"
                           class="recommendInput hide" v-model="order.GROWTH_RATE">
                </td>
                <td>{{order.LAST_NUM}}</td>

                <td onclick="clickRecommendNum(this);">
                    <span>{{order.LAST_GR}}</span>
                    <input min="0" onclick="stopD()" @blur="computeRecommend1(index,$event)" type="number"
                           class="recommendInput hide" v-model="order.LAST_GR">
                </td>

                <td onclick="clickRecommendNum(this);">
                    <span>{{order.RECOMMEND_NUM}}</span>
                    <input min="0" onclick="stopD()" onblur="$(this).parent().click()" type="number"
                           class="recommendInput hide" v-model="order.RECOMMEND_NUM">
                </td>
                <td>{{computePC(order.CURRENT_ALREADY,order.RECOMMEND_NUM)}}</td>
                <td>{{computeDOD(order.CURRENT_ALREADY,order.RECOMMEND_NUM)}}</td>
                <%--<td>{{order.OPERATOR_TIME}}</td>--%>
            </tr>
            </tbody>
        </table>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" data-backdrop="static" role="dialog"
         aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">添加品规的增长率</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" role="form">
                        <div class="form-group">
                            <label class="col-sm-3 control-label">客户：</label>
                            <div class="col-sm-8">
                                <input class="form-control" onfocus="this.value=''" id="add_cust_code" placeholder="请选择客户">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">年月：</label>
                            <div class="col-sm-8">
                                <input class="form-control" id="add_yearMoth" placeholder="请选择年月">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-3 control-label">推荐量：</label>
                            <div class="col-sm-8">
                                <input class="form-control" id="add_recommend_num" placeholder="请输入推荐量">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" @click="submitData">确定</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="${contextPath}/static/statistics/js/vue.js"></script>
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script type="text/javascript">
    var laypage = layui.laypage
        , layer = layui.layer;

    var app = new Vue({
        el: '#app',
        data: {
            isAllS: false,
            orderList: [],
            customers: [],
            prods: [],
        },
        methods: {
            getInitData: function () {
                var vm = this;
                $.ajax({
                    url: '${contextPath}/shop/getRecommendCustAndProdData',
                    type: 'get',
                    dataType: 'json',
                    async: false,
                    success: function (data) {
                        if (data.success) {
                            vm.customers = data.data.customers;
                            vm.prods = data.data.prods;
                            $('#custCodeInput').autocomplete({
                                lookup: vm.customers,
                                minChars: 0,
                            })
                            $('#add_cust_code').autocomplete({
                                lookup: vm.customers,
                                minChars: 0,
                            });
                        } else {
                            layer.msg('获取客户和烟品信息失败失败');
                        }

                    },
                    error: function (error) {
                        if (window.console) console.error(error);
                        layer.msg('网络错误');
                    }
                });

                $('#yearMothInput').datetimepicker({
                    language: 'zh-CN',
                    weekStart: 1,
                    todayBtn: 1,
                    autoclose: 1,
                    todayHighlight: 1,
                    startView: 3,
                    forceParse: 0,
                    minView: 3,
                    showMeridian: 1,
                    format: "yyyy-mm",
                });

                var day1 = new Date();
                //day1.setTime(day1.getTime()-24*60*60*1000);

                var year = day1.getFullYear();
                var month = day1.getMonth() + 1 ;
                if (month < 10) {
                    month = '0' + month
                }
                var defauteYearMonth = year + '-' + month;
                $('#yearMothInput').val(defauteYearMonth);

                $('#add_yearMoth').datetimepicker({
                    language: 'zh-CN',
                    weekStart: 1,
                    todayBtn: 1,
                    autoclose: 1,
                    todayHighlight: 1,
                    startView: 3,
                    forceParse: 0,
                    minView: 3,
                    showMeridian: 1,
                    format: "yyyy-mm",
                });


            },
            submitData: function () {
                var custCode = $("#add_cust_code").val();
                var yearMoth = $("#add_yearMoth").val();
                var rn = $("#add_recommend_num").val();

                if (!custCode) {
                    layer.msg('请选择客户');
                    return;
                }
                if (!yearMoth) {
                    layer.msg('请输入年月');
                    return;
                }
                if (!rn) {
                    layer.msg('请输入推荐量');
                    return;
                }
                layer.load(1);
                $.ajax({
                    url: '${contextPath}/shop/addRecommendDataGR',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        stringMap: {
                            CUST_CODE: custCode,
                            YEAR_MOTH: yearMoth,
                            RECOMMEND_NUM: rn,
                        }
                    },
                    //async : false,
                    success: function (data) {
                        layer.closeAll('loading');
                        layer.msg(data.message);
                        if (data.success) {
                            $('#myModal').modal('hide')
                        }

                    },
                    error: function (error) {
                        layer.closeAll('loading');
                        if (window.console) console.error(error);
                        layer.msg('网络错误');
                    }
                });


            },
            getOrder: function () {
                var vm = this;

                var custCode = $("#custCodeInput").val();
                var yearMoth = $("#yearMothInput").val();
                layer.load(1);
                $.ajax({
                    url: '${contextPath}/shop/getRecommendOrderGRList',
                    type: 'post',
                    data: {
                        stringMap: {
                            custCode: custCode,
                            yearMoth: yearMoth,
                        },
                    },
                    success: function (data) {
                        layer.closeAll('loading')
                        if (data.success == false) {
                            layer.msg("获取出错：" + data.message)
                            return
                        }
                        //console.log(data)
                        var rData = data.data;
                        if (rData.length == 0) {
                            layer.msg("查询没有数据")
                        }
                        app.orderList = rData;
                        app.isAllS = false;
                    },
                    error: function (error) {
                        layer.closeAll('loading');
                        layer.msg('网络错误');
                        if (window.console) console.log(error)
                    }
                })
            },
            computeRecommend: function () {
                layer.load(1);
                //同期 * 增长率 - 已购 ／ 所剩周数
                var resultList = []
                for (var index in this.orderList) {
                    var order = this.orderList[index];
                    if (order.CHECK || !order.RECOMMEND_NUM || order.RECOMMEND_NUM == '0') {
                        var tcpNum = order.TCP_NUM ? new Number(order.TCP_NUM) : 0;
                        var lastNum = order.LAST_NUM ? new Number(order.LAST_NUM) : 0;
                        var gr = order.GROWTH_RATE ? new Number(order.GROWTH_RATE) : 0;
                        var lastGr = order.LAST_GR ? new Number(order.LAST_GR) : 0;

                        var rn = 0;

                        if (tcpNum && gr) {
                            rn = tcpNum * gr;
                        }
                        if (lastNum && lastGr) {
                            rn = lastNum * lastGr
                        }
                        if (tcpNum && gr && lastNum && lastGr) {
                            rn = (tcpNum * gr + lastNum * lastGr) / 2
                        }
                        var n = Math.ceil(rn);
                        if (n <= 0) {
                            n = 0
                        }
                        order.RECOMMEND_NUM = n;
                    }
                    resultList.push(order)
                }
                this.orderList = resultList
                layer.closeAll('loading');
            },
            revocation: function (index) {
                var indx = layer.confirm('确定要撤销吗？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    console.log(app.orderList[index])
                    layer.close(indx);
                    layer.load(1)
                    //修改订单状态
                    $.ajax({
                        url: '${contextPath}/shop/revocationCourier',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            stringMap: app.orderList[index]
                        },
                        success: function (data) {
                            layer.closeAll('loading');
                            layer.msg(data.message);
                            if (data.success) {
                                app.getOrder();
                            }
                        },
                        error: function (error) {
                            layer.msg("网络错误");
                            layer.closeAll('loading')
                        }
                    });
                }, function () {
                });
            },
            clickAllSB: function () {
                this.isAllS = !this.isAllS;
                for (var index in this.orderList) {
                    this.orderList[index].CHECK = this.isAllS
                }

            },
            saveData: function () {
                var saveDs = [];
                for (var index in this.orderList) {
                    var order = this.orderList[index];
                    if (order.CHECK) {
                        saveDs.push(order)
                    }
                }
                if (saveDs.length == 0) {
                    layer.msg('请至少选择一条需要保存的数据')
                    return;
                }
                layer.load(1);
                $.ajax({
                    url: '${contextPath}/shop/updateRecommendOrderGR',
                    type: 'post',
                    data: {
                        data: JSON.stringify(saveDs),
                    },
                    success: function (data) {
                        layer.closeAll('loading')
                        if (!data.success) {
                            layer.msg("保存出错：" + data.message)
                            return
                        }
                        layer.msg('保存成功');

                    },
                    error: function (error) {
                        layer.closeAll('loading');
                        layer.msg('网络错误');
                        if (window.console) console.log(error)
                    }
                })
            },
            saveDataAs: function () {

                var custCode = $("#custCodeInput").val();
                if (!custCode) {
                    layer.msg('请选择专卖证号');
                    return;
                }
                var year = $("#yearInput").val();
                if (!year) {
                    layer.msg('请选择年');
                    return;
                }
                var week = $("#weekInput").val();
                if (!week) {
                    layer.msg('请选择年周');
                    return;
                }

                var title = "<div>将列表中选中品规推荐量存到</div>" + "<div>客户：" + "<span style='color: #0aa5df'>" + custCode + "</span>" + "</div>" + "<div>" + "<span style='color: #0aa5df'>" + year + "</span>" + "年，第" + "<span style='color: #0aa5df'>" + week + "</span>" + "周" + "</div>";

                var indx = layer.confirm(title, {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    layer.close(indx);
                    app.saveData(custCode, year, week);
                }, function () {
                });
            },
            computePC: function (ca, rn) { //这是个方法，却可以根据实参的变化而被动态调用，从而返回新的值，在显示处体现出来
                if (ca && ca != '0' && rn && rn != '0') {
                    return (ca / rn * 100).toFixed(2) + '%'
                }
                return ''
            },
            computeDOD: function (ca, rn) { //这是个方法，却可以根据实参的变化而被动态调用，从而返回新的值，在显示处体现出来
                if (ca && ca != '0' && rn && rn != '0') {
                    return Math.abs((ca / rn).toFixed(2) *100 -100)
                }
                return ''
            },
            addRecommend: function () {

                var custCode = $("#custCodeInput").val();

                $("#add_cust_code").val(custCode);

                var yearMoth = $("#yearMothInput").val();
                $("#add_yearMoth").val(yearMoth);
                $('#myModal').modal('show')
            },
            computeRecommend1: function (index, e) {
                e.target.parentNode.click();
                var order = this.orderList[index];
                var tcpNum = order.TCP_NUM ? new Number(order.TCP_NUM) : 0;
                var lastNum = order.LAST_NUM ? new Number(order.LAST_NUM) : 0;
                var gr = order.GROWTH_RATE ? new Number(order.GROWTH_RATE) : 0;
                var lastGr = order.LAST_GR ? new Number(order.LAST_GR) : 0;

                var rn = order.RECOMMEND_NUM ? order.RECOMMEND_NUM : 0;

                if (tcpNum && gr) {
                    rn = tcpNum * gr;
                }
                if (lastNum && lastGr) {
                    rn = lastNum * lastGr
                }
                if (tcpNum && gr && lastNum && lastGr) {
                    rn = (tcpNum * gr + lastNum * lastGr) / 2
                }
                var n = Math.ceil(rn);
                if (n <= 0) {
                    n = 0
                }
                order.RECOMMEND_NUM = n;
            },
            goToRecommendPage : function (custCode, yearMoth, cn, rn) {
                localStorage.custCode = custCode;
                localStorage.yearMoth = yearMoth;
                localStorage.cn = cn ? cn : '0';
                localStorage.rn = rn ? rn : '0' ;
                window.location.hash="page/clouderpOrderRecommend"
            }

        },
        watch: {}
    })
    app.getInitData();

    app.getOrder();


    function clickRecommendNum(vm) {
        var $span = $(vm).children("span:first-child");
        var $input = $(vm).children("input:last-child");
        if ($span.hasClass("hide")) {
            $span.removeClass("hide")
            $input.addClass("hide")
        } else {
            $span.addClass("hide")
            $input.removeClass("hide");
            $input.focus();
        }
    }

    function stopD() {
        cancelBubble();
    }

    function cancelBubble(e) {
        var evt = e ? e : window.event;
        if (evt.stopPropagation) {        //W3C
            evt.stopPropagation();
        } else {       //IE
            evt.cancelBubble = true;
        }
    }
</script>


